//
//  CLTabBar.swift
//  CLWeibo
//
//  Created by 陈亮 on 16/7/9.
//  Copyright © 2016年 陈亮. All rights reserved.
//

import UIKit
//定义协议必须继承自NSObjectProtocol
protocol CLTabBarDelegate:NSObjectProtocol {
    func didClickComposeButton ()
}

class CLTabBar: UITabBar {

    //创建中间按钮的闭包
    var composeButtonClosure:(()->())?
    //定义代理对象
    weak var clDelegate:CLTabBarDelegate?
    //懒加载

    private lazy var composeButton: UIButton = {
        //创建按钮
        let button = UIButton()
        //添加点击事件
        button.addTarget(self, action: "composeButtonClick", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        //按钮设置大小
        button.sizeToFit()
        return button
        
    }()
    // MARK:  撰写按钮点击事件
    func composeButtonClick () {
        
        composeButtonClosure?()
    }
    //结构体函数
    override init(frame: CGRect) {
        super.init(frame:frame)
        addSubview(composeButton)
        //调用代理方法
        clDelegate?.didClickComposeButton()
    }
    

    //加载XIB或者SB 会调用这个函数
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //布局Frame
    override func layoutSubviews() {
        super.layoutSubviews()
        //  设置撰写按钮的中心点
        composeButton.centerX = width * 0.5
        composeButton.centerY = height * 0.5
        //  获取系统控件
        //  计算控件的宽度
        let itemWidth = width / 5
        //  记录遍历是第一个按钮
        var index = 0
        for value in subviews {
            //  这个类是私有 UITabBarButton.self 获取class
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                value.x = CGFloat(index) * itemWidth
                value.width = itemWidth
                if index == 1 {
                    index++
                }
                index++
            }
            
        }
        
        
        
        
        
    }
}
